<?php

/**
 * 签约业绩仓库
 * @author wangwx 2015-5-12
 */

namespace common\repositories\myhtsq;

use common\entities\ConfigEntity;
use common\entities\ContractEntity;
use common\repositories\BaseRepository;
use common\repositories\common\MyscrmContractSyncDeleteDataRepository;
use common\support\StringHelper;
use common\entities\myhtsq\SignAchievementEntity;
use common\models\myhtsq\SignAchievementModel;
use common\entities\myhtsq\ContractPropertyEntity;

class SignAchievementRepository extends BaseRepository
{

    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = [])
    {
        parent::__construct($config);
    }

    /**
     * 根据合同id,获取合同业绩列表
     * @param string $contractId 合同id
     * @return array
     */
    public static function getSignAchievementListByContractId($contractId)
    {
        return SignAchievementEntity::find()->where(['contract_id' => $contractId])->asArray()->all();
    }

    /**
     * 根据签约id,删除签约业绩
     * @param string $achievementId 签约id
     * @return boolean
     */
    public static function deleteSignAchievementByAchievementId($achievementId)
    {
        /** @var MyscrmContractSyncDeleteDataRepository $contractSyncDeleteDataRepository */
        $contractSyncDeleteDataRepository = \Yii::createObject(MyscrmContractSyncDeleteDataRepository::className());

        $deleteResult = SignAchievementEntity::deleteAll(['achievement_id' => $achievementId]);

        if ($deleteResult > 0) {
            $contractSyncDeleteDataRepository->add('myscrm_sign_achievement', 'achievement_id', $achievementId);
        }

        return $deleteResult;
    }

    /**
     * 新增签约业绩
     * @param \common\models\myhtsq\SignAchievementModel $signAchievementModel 签约业绩模型
     * @return boolean|string
     */
    public static function addSignAchievement(SignAchievementModel $signAchievementModel)
    {
        $signAchievementEntity = new SignAchievementEntity();
        $data = $signAchievementModel->attributes;
        $signAchievementEntity->load($data, '');
        $signAchievementEntity->achievement_id = StringHelper::uuid();
        if ($signAchievementEntity->save()) {
            return $signAchievementEntity->achievement_id;
        } else {
            return false;
        }
    }

    /**
     * 更新签约业绩
     * @param \common\models\myhtsq\SignAchievementModel $signAchievementModel 签约业绩模型
     * @return string|boolean
     */
    public static function updateSignAchievement(SignAchievementModel $signAchievementModel)
    {
        $signAchievementEntity = new SignAchievementEntity();
        $signAchievementModelInfo = $signAchievementEntity::find()->where(['achievement_id' => $signAchievementModel->achievement_id])->one();
        $data = $signAchievementModel->attributes;
        $signAchievementModelInfo->load($data, '');
        if ($signAchievementModelInfo->save()) {
            return $signAchievementModelInfo->achievement_id;
        } else {
            return false;
        }
    }

    /**
     * 根据合同id,获取合同的签约业绩总额
     * @param string $contractId 合同id
     * @return float
     */
    public static function getSignAchievementSumByContractId($contractId)
    {
        return SignAchievementEntity::find()->where(['contract_id' => $contractId])->sum('achievement_amount');
    }

    /**
     * 保存或修改合同基本时，对签约信息进行处理
     * 云客签约-直属区域/云客签约-联营区域 : 收入金额汇总 = 签约金额
     * 明源签约-直属区域/明源签约-联营区域 /联营签约-明源结算/联营签约-云客结算:收入金额汇总=结算金额
     * @param string $type 处理类型：add(新增),update(更新)
     * @param string $contractId 合同id
     * @param string $contractPropertyId 合同性质id
     * @param string $areaId 区域id
     * @param string $signPeopleId 签约人id
     * @return boolean
     */
    public static function handleContractSignAchievement($type, $contractId, $contractPropertyId, $areaId, $signPeopleId, $signAmount = 0, $balanceAmount = 0)
    {

        $signAchievementAmount = 0;
        if ($type == 'add') { //新建合同
            //云客签约-直属区域/云客签约-联营区域 : 收入金额汇总 = 签约金额
            if ($contractPropertyId == ContractPropertyEntity::MYYK_PROPERTY_DIRECTLY_UNDER_ID || $contractPropertyId == ContractPropertyEntity::MYYK_PROPERTY_JOINT_OPERATION_ID || $contractPropertyId == ContractPropertyEntity::MYYK_PROPERTY_DIRECT_SALES_ID) {
                $signAchievementAmount = $signAmount;
            } else {
                //明源签约-直属区域/明源签约-联营区域 /联营签约-明源结算/联营签约-云客结算:收入金额汇总=结算金额
                $signAchievementAmount = $balanceAmount;
            }
            $signAchievementModel = new SignAchievementModel();
            $signAchievementModel->setScenario('add');
            $signAchievementModel->achievement_id = StringHelper::uuid();
            $signAchievementModel->contract_id = $contractId;
            $signAchievementModel->achievement_amount = $signAchievementAmount;
            $signAchievementModel->belong_by = $signPeopleId;
            $signAchievementModel->department_by = '';
            $signAchievementModel->area_by = $areaId;
            $signAchievementModel->manager_by = '';
            $signAchievementModel->achievement_belong_time = date("Y-m-d", ContractEntity::getDbNowTimestamp());
            $signAchievementModel->fillBuInfoByUser();
            if (SignAchievementRepository::addSignAchievement($signAchievementModel)) {
                return true;
            } else {
                return false;
            }
        } else {//更新合同
            $contractManageModel = ContractManageRepository::getContractManageModelByContractId($contractId);

            $amount = self::getSignAchievementSumByContractId($contractId); //业绩签约金额

            $signAchievementAmount = 0; //默认值
            //云客签约-直属区域/云客签约-联营区域 : 收入金额汇总 = 签约金额
            if ($contractPropertyId == ContractPropertyEntity::MYYK_PROPERTY_DIRECTLY_UNDER_ID || $contractPropertyId == ContractPropertyEntity::MYYK_PROPERTY_JOINT_OPERATION_ID || $contractPropertyId == ContractPropertyEntity::MYYK_PROPERTY_DIRECT_SALES_ID) {
                if ($contractManageModel->sign_amount != $amount) {
                    $signAchievementAmount = $contractManageModel->sign_amount;
                } else {
                    return true;
                }
            } else {
                //明源签约-直属区域/明源签约-联营区域 /联营签约-明源结算/联营签约-云客结算:收入金额汇总=结算金额
                if ($contractManageModel->balance_amount != $amount) {
                    $signAchievementAmount = $contractManageModel->balance_amount;
                } else {
                    return true;
                }
            }

            /** @var MyscrmContractSyncDeleteDataRepository $contractSyncDeleteDataRepository */
            $contractSyncDeleteDataRepository = \Yii::createObject(MyscrmContractSyncDeleteDataRepository::className());

            $deleteData = SignAchievementEntity::findAll(['contract_id' => $contractId]);

            $deleteResult = SignAchievementEntity::deleteAll(['contract_id' => $contractId]); //把签约业绩，先删后插

            if ($deleteResult > 0) {
                foreach ($deleteData as $data) {
                    $contractSyncDeleteDataRepository->add('myscrm_sign_achievement', 'achievement_id', $data['achievement_id']);
                }
            }

            $signAchievementModel = new SignAchievementModel();
            $signAchievementModel->setScenario('add');
            $signAchievementModel->achievement_id = StringHelper::uuid();
            $signAchievementModel->contract_id = $contractId;
            $signAchievementModel->achievement_amount = $signAchievementAmount;
            $signAchievementModel->belong_by = $signPeopleId;
            $signAchievementModel->department_by = '';
            $signAchievementModel->area_by = $areaId;
            $signAchievementModel->manager_by = '';
            $signAchievementModel->achievement_belong_time = $contractManageModel->input_date;
            $signAchievementModel->fillBuInfoByUser();
            if (SignAchievementRepository::addSignAchievement($signAchievementModel)) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 更新业绩归属时间
     * @param $contract_id
     * @param $time
     * @return int
     */
    public static function updateBelongTime($contract_id, $time)
    {
        return SignAchievementEntity::updateAll(['achievement_belong_time' => $time], ['contract_id' => $contract_id]);
    }

    /**
     * 根据合同号删除
     * @param $contractId
     * @return int
     */
    public static function deleteByContractId($contractId)
    {
        /** @var MyscrmContractSyncDeleteDataRepository $contractSyncDeleteDataRepository */
        $contractSyncDeleteDataRepository = \Yii::createObject(MyscrmContractSyncDeleteDataRepository::className());

        $deleteData = SignAchievementEntity::findAll(["contract_id" => $contractId]);

        $deleteResult = SignAchievementEntity::deleteAll(["contract_id" => $contractId]);

        if($deleteResult > 0){
            foreach ($deleteData as $data){
                $contractSyncDeleteDataRepository->add('myscrm_sign_achievement', 'achievement_id', $data['achievement_id']);
            }
        }

        return $deleteResult;
    }
}
